package com.lxhdj.management.security;


import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author TangDan
 * @version 1.0
 * @since 2023/4/7
 */
public class CustomAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsServiceImpl userDetailsServiceImpl;

    private PasswordEncoder passwordEncoder;

    public CustomAuthenticationProvider(UserDetailsServiceImpl userDetailsServiceImpl, PasswordEncoder passwordEncoder) {
        this.userDetailsServiceImpl = userDetailsServiceImpl;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        Object principal = authentication.getPrincipal();// 获取凭证也就是用户的手机号
        String phone = "";
        if (principal instanceof String) {
            phone = (String) principal;
        }
        String inputCode = (String) authentication.getCredentials(); // 获取输入的密码

        // 2. 根据手机号查询用户信息
        UserDetail userDetails = (UserDetail) userDetailsServiceImpl.loadUserByUsername(phone);

        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("phone用户不存在，请注册");
        }
        if (!passwordEncoder.matches(inputCode, userDetails.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        // 3. 创建已认证对象
        UsernamePasswordAuthenticationToken authenticationResult = new UsernamePasswordAuthenticationToken(userDetails,inputCode, userDetails.getAuthorities());
        authenticationResult.setDetails(userDetails.getUserModel());
        return authenticationResult;
    }


    @Override
    public boolean supports(Class<?> aClass) {
        // 当 SmsAuthenticationToken 认证时，匹配该类
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
